import { mapState, mapMutations } from 'vuex';
import WSK from '../../../assets/websocket.js';


import { config } from '../../../Axios/config.js';
const md5 = require('md5');

export default {
  name: 'appWs',
  components: {},
  computed: {
    ...mapState([
      'loginInfo',
      'wsMsgFromApp',
      'wsMsgToApp',
    ])
  },
  data() {
    return {
      isDev: process.env.NODE_ENV == 'development',
      status: {
        isOpen: false,
        noError: true,
        isHeaet: false,
      },
      webSocket: null,//建立的连接
      wsKey: '',
      wh: 0,//mounted中赋值,$notify 中作为参数
      n: 1,

      timeHeart: 1000 * 6,

    };
  },
  watch: {
    '$store.state.wsMsgToApp': {
      deep: true,
      handler: function (nv, ov) {
        let msg = nv;
        this.webSocket.send(msg)
      }
    },
  },
  methods: {
    test() {
      console.log(`this is ${this.$options.name}`)
    },
    initWebSocket: function (key) {
      let self = this;
      self.webSocket = new WSK({
        isAutoLink: true,
        // host: 'ws://192.168.11.50:8181',
        host: config.appWs,
        timeHeart: self.timeHeart,
        strBegin: '',
        strEnd: '<EOF>',
        strHeart: 'KEEPALIVE',
        wsObj: Object.assign(
          { "SourceCode": 5, "Users_Id": key }
          // this.$store.getters.getCEID(false),
          // { "msgtype": 1 }
        ),
        beforeOpen: () => { this.status.isOpen = false; },
        afterOpen: () => { this.status.isOpen = true; },
        beforeSendHeart: (ws) => { this.status.isHeaet = false; },
        afterGetHeart: (ws) => { this.status.isHeaet = true; },
        beforeMessage: (ws, msg, e) => {
          return Promise.resolve(msg)
        },
        afterMessage: (ws, jsonMsg, e) => {
          this.msgHandle(jsonMsg)
        },
        beforeError: (err) => {
          this.status.noError = false;
          this.$message({
            type: 'error',
            message: `${this.$options.name}socket连接出现错误，尝试重连中...`,
            duration: 0,
            showClose: true,
          });
        },
        afterClose: (err) => {
          this.status.isOpen = false;
          this.$alert(
            `${this.$options.name}socket已关闭，如需请手动重启`,
            '提示',
            {
              type: 'error',
              center: true,
              confirmButtonText: '刷新重连',
            }
          ).then(() => {
            location.reload()
          })
        },
      });
      self.webSocket.start();
      return `${self.$options.name}初始化完成`;
    },
    msgHandle: function (jsonMsg) {
      // this.$store.commit('updataWsMsgIn', {
      //   from: this.$options.name,
      //   msg: jsonMsg
      // });
      if (jsonMsg.msgtype == '62') {//登录相关信息
        return;
      }
      if (jsonMsg.msgtype == "61") {
        this.$store.commit('updataWsMsgIn', {
          from: this.$options.name,
          msg: jsonMsg
        });
        return;
      }
      if (jsonMsg.msgtype == '11') {//单点登录被异地强制下线
        this.webSocket.stop();
        this.$message({
          message: '您的账号已下线，请刷新重新连接',
          type: 'error'
        });
        return;
      }
    }
  },
  mounted() {
    this.wh = window.innerHiehgt || document.documentElement.clienHeight || document.body.clientHeight
  },
  beforeUpdate() {

  },
  updated() {

  },
  beforeDestroy() {
    this.webSocket.stop();
  },
  destroyed() {
    this.webSocket.stop();
  },

}

/*
有用的消息格式
msgtype:61,
msgId:消息ID,
usersId:客户UserId,
isFromUser:消息是否是员工发的,
nicheng:客户的昵称,
imgUrl:客户的头像,
msgBody:聊天内容,
type:消息类型：0=文字，1=图片,
imgW:图片宽度,
imgH:图片高度,
addTime:发送时间
*/